<template>
    <div>
        <el-tabs v-model="activeName">
            <el-tab-pane label="基础信息" name="Datas">
                <el-form :model="model" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="订单编号" prop="Number">
                                <el-input v-model="model.Number" placeholder="请输入订单编号"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="备注" prop="Remark">
                                <el-input v-model="model.Remark" placeholder="备注信息"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="收款账户" prop="PaymentAccount">
                                <el-select v-model="model.PaymentAccount" placeholder="收款账户">
                                    <el-option label="建设银行" value="建设银行"></el-option>
                                    <el-option label="微信" value="微信"></el-option>
                                    <el-option label="支付宝" value="支付宝"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="出库日期" prop="DeliveryDate">
                                <el-date-picker type="date" placeholder="选择日期" v-model="model.DeliveryDate"
                                    style="width: 100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>


                        <el-col :span="8">
                            <el-form-item label="关联订单" prop="OrderSalesId">
                                <el-input v-model="model.OrderSalesId" :readonly="true"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="总数量" prop="Count">
                                <el-input v-model="model.Count" :readonly="true"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="客户" prop="CustomerNumber">
                                <el-select :value="model.CustomerName" placeholder="请选择客户" @change="CustomerChange">
                                    <el-option v-for="Customer in ClientList" :key="Customer.Id"
                                        :label="Customer.ClientName" :value="Customer"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="联系人" prop="CustomerContact">
                                <el-input v-model="model.CustomerContact" placeholder="请输入客户联系人"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="联系电话" prop="CustomerContactTel">
                                <el-input v-model="model.CustomerContactTel" placeholder="请输入客户联系人电话"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="交货地址" prop="DeliveryLocation">
                                <el-input v-model="model.DeliveryLocation" placeholder="请输入交货地址"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="收款方式" prop="PaymentCategory">
                                <el-select v-model="model.PaymentCategory" placeholder="收款方式">
                                    <el-option label="现金支付" value="现金支付"></el-option>
                                    <el-option label="银行卡转账" value="银行卡转账"></el-option>
                                    <el-option label="微信" value="微信"></el-option>
                                    <el-option label="支付宝" value="支付宝"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="收款日期" prop="PaymentTime">
                                <el-date-picker type="date" placeholder="收款日期" v-model="model.PaymentTime"
                                    style="width: 100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="运输方式" prop="Transfer">
                                <el-select v-model="model.Transfer">
                                    <el-option label="公路运输" value="公路运输"></el-option>
                                    <el-option label="铁路运输" value="铁路运输"></el-option>
                                    <el-option label="水路运输" value="水路运输"></el-option>
                                    <el-option label="航空运输" value="航空运输"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="出库仓" prop="WarehouseId">
                                <el-select :value="model.WarehouseName" placeholder="请选择出库仓" @change="WarehouseChange">
                                    <el-option v-for="Warehouse in WarehouseList" :key="Warehouse.Id"
                                        :label="Warehouse.WarehouseName" :value="Warehouse"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="总价" prop="Price">
                                <el-input v-model="model.Price" :readonly="true"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="优惠" prop="DisCount">
                                <el-input v-model="model.DisCount" :readonly="true"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="订单状态" prop="Status">
                                <el-select v-model="model.Status">
                                    <el-option label="待审核" value=0></el-option>
                                    <el-option label="已审核" value=1></el-option>
                                    <el-option label="已退货" value=2></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>


                </el-form>
            </el-tab-pane>
            <el-tab-pane label="添加商品" name="AddProduct">
                <div class="page-tool">
                    <el-button type="primary" plain icon="el-icon-plus" @click="addProduct" size="small">新增</el-button>
                    <el-button type="danger" plain icon="el-icon-delete" size="small" @click="delProduct">删除</el-button>
                </div>
                <el-table :data="tableData" ref="dataForm" v-loading="isLoading" height="360" show-summary
                    :summary-method="getSummaries">
                    <el-table-column type="selection" width="70"></el-table-column>
                    <el-table-column prop="ItemCode" label="物料编码" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="ItemName" label="物料名称" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="Spec" label="规格" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="UnitOfMeasure" label="单位" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="Amount" label="金额" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="CurrCount" label="当前库存" :show-overflow-tooltip="true"></el-table-column>

                    <el-table-column prop="Count" label="数量" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.Count" @change="handleTaxChange(scope.row)" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="Price" label="商品单价" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.Price" @change="handleTaxChange(scope.row)"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column prop="Rebate" label="返利" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.Rebate" @change="handleTaxChange(scope.row)"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column prop="Remark" label="备注" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.Remark" ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <el-button type="text" @click="del(scope.row)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </el-tab-pane>

        </el-tabs>
        <div class="page-form-action">
            <el-button  @click="addOrderSale" >选择单据</el-button>
            <el-button @click="resetForm">重置</el-button>
            <el-button type="primary" @click="submitForm">{{ isUpdate ? '立即保存' : '立即创建' }}</el-button>
        </div>


        <el-dialog append-to-body :close-on-click-modal="false" :title="dialogDomain.title"
            :visible.sync="dialogDomain.dialogVisible" width="60%">
            <SelectedOrderSale @callback="OrderSaleCallBack" :BomList="OrderSaleList"
                v-if="dialogDomain.dialogVisible && dialogDomain.dialogType == 0" />
            <ProductBom @callback="CallBack" :ItemList="tableData" :WareHouseId="model.WarehouseId.toString()"
                v-else-if="dialogDomain.dialogVisible && dialogDomain.dialogType == 1" />

        </el-dialog>

    </div>
</template>

<script>
import ProductBom from '@/views/Product/ProductView/components/SelectedItemFourStock.vue'
import SelectedOrderSale from './SelectedOrderSale.vue'
export default {
    components: {
        ProductBom,
        SelectedOrderSale
    },
    props: {
        model: {
            require: true,
            type: Object
        },
        isUpdate: {
            require: true,
            type: Boolean
        },
        WarehouseList: {
            type: Array,
            required: true

        },
        ClientList: {
            type: Array,
            required: true

        },
    },
    data() {
        return {

            activeName: 'Datas',
            ProProcessList: [],
            rules: {
                WorkorderCode: { required: true, message: '请输入生产订单编号', trigger: 'blur' },
                OrderSource: { required: true, message: '请选择订单来源', trigger: 'blur' },
                ProductCode: { required: true, message: '请选择产品编号' },
            },
            DepartmentList: [],
            SystemPostList: [],
            tableData: [],
            isLoading: false,
            dialogDomain: {
                title: '物料产品选择',
                dialogVisible: false,
            },
            OrderSaleList: [],
            rules: {
                Number: { required: true, message: '请输入单号', trigger: 'blur' },
                CustomerNumber: { required: true, message: '请选择客户', trigger: 'blur' },
                CustomerContact: { required: true, message: '请输入联系人名称', trigger: 'blur' },
                CustomerContactTel: { required: true, message: '请输入联系人电话', trigger: 'blur' },
                WarehouseId: { required: true, message: '请选择出库仓' },
                DeliveryLocation: { required: true, message: '请输入交货地址', trigger: 'blur' },
                PaymentCategory: { required: true, message: '请选择收款方式', trigger: 'blur' },
                PaymentAccount: { required: true, message: '请选择收款账户', trigger: 'blur' },
                PaymentTime: { required: true, message: '请选择收款日期', trigger: 'blur' },
                Transfer: { required: true, message: '请选择运输方式', trigger: 'blur' },
            }
        }
    },
    created() {
        if (this.isUpdate)
            this.GetItem()
    },
    methods: {
        del(model) {
            let index = this.tableData.indexOf(model);
            this.tableData.splice(index, 1);

            this.calcPrice();
        },
        submitForm() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {

                    if (this.isUpdate) {
                        this.put();
                    }
                    else {
                        this.add();
                    }

                } else {
                    this.showNotify('请输入必填项');
                    return false;
                }
            });
        },
        resetForm() {
            this.$refs['ruleForm'].resetFields();
        },
        add() {
            console.log(this.model)
            this.$http.postForm('/api/OrderSalesExWarehouse', { model: this.model, OrderSalesExWarehouseItemString: JSON.stringify(this.tableData) }, { loading: this.$loading() })
                .then(res => {
                    this.$emit('callback');
                })

        },
        //修改
        put() {
            this.$http.putForm('/api/OrderSalesExWarehouse', { model: this.model, OrderSalesExWarehouseItemString: JSON.stringify(this.tableData) }, { loading: this.$loading() })
                .then((res) => {
                    this.$emit('callback');
                })
        },
        addProduct() {
            if (this.model.WarehouseId == "") {
                this.showNotify('请选择仓库');
                return;
            }
            this.dialogDomain.title = "选择产品分类";
            this.dialogDomain.dialogVisible = true;
            this.dialogDomain.dialogType = 1;
        },
        delProduct(){
            if (this.$refs.dataForm.selection.length <= 0) {
                this.showNotify('请选择一项');
                return;
            }
            this.$refs.dataForm.selection.forEach(row => {
                const index = this.tableData.indexOf(row);
                this.tableData.splice(index, 1);
            });
            this.calcPrice();
        },
        CallBack() {
            let arr = [];
            this.tableData.map(x => {
                var obj = new Object();
                //处理所需字段
                this.$set(obj, 'ItemId', x.ItemId);
                this.$set(obj, 'ItemCode', x.ItemCode);
                this.$set(obj, 'ItemName', x.ItemName);
                this.$set(obj, 'CurrCount', x.CurrCount);
                this.$set(obj, 'Rebate', 1);
                this.$set(obj, 'Amount', x.SalePrice );
                this.$set(obj, 'Price', x.SalePrice);
                this.$set(obj, 'Count', 1);
                this.$set(obj, 'Remark', '');
                this.$set(obj, 'Spec', x.Spec);
                this.$set(obj, 'UnitOfMeasure', x.UnitOfMeasure);
                arr.push(obj);
            })

            this.tableData = arr;
            this.dialogDomain.dialogVisible = false;
            this.calcPrice();
        },
        GetItem() {
            this.isLoading = true;
            this.$http.get('/api/OrderSalesExWarehouse/GetItem', {
                params: {
                    WarehouseId: this.model.WarehouseId,
                    OrderSalesExWarehouseId: this.model.Id,
                }
            })
            .then(res => {
                res.Data.map(x=>{
                    x.CurrCount = x.CurrCount + x.Count;
                })
                this.tableData = res.Data;
                this.isLoading = false;
            })
        },
        WarehouseChange(model) {
            this.model.WarehouseId = model.Id;
            this.model.WarehouseName = model.WarehouseName
            console.log(model)
        },
        CustomerChange(model) {
            this.model.CustomerNumber = model.Id;
            this.model.CustomerName = model.ClientName;
            console.log(model)
        },

        calcPrice() {
            //计算总价
            let sum = 0.0;
            let count = 0;
            let disCount = 0.0;
            this.tableData.map(item => {
                sum += item.Amount;

                if (item.Rebate < 0) {
                    sum += item.Price * item.Count * item.Rebate;
                }
                disCount+=(item.Price*item.Count) -(item.Price * item.Count * item.Rebate) ;

                count+=Number(item.Count);
            })
            this.model.Price = sum;
            this.model.Count = count;
            this.model.DisCount = disCount;

        },



        handleTaxChange(row) {


            if(row.Count > row.CurrCount){
                row.Count = row.CurrCount;
                this.showNotify('输入的出库数量大于剩余库存，已将剩余库存作为出库数量。');
            }

            // 获取用户输入的返利
            row.Amount = row.Count * row.Price;//金额
            if (row.Rebate < 1) {
                row.Amount = row.Count * row.Price * row.Rebate;//金额
            }

            this.calcPrice();

        },

        addOrderSale() {
            this.dialogDomain.title = "选择单据";
            this.dialogDomain.dialogVisible = true;
            this.dialogDomain.dialogType = 0;
        },
        OrderSaleCallBack(model,list) {
            console.log(model,list);
            this.dialogDomain.dialogVisible = false;

            this.model.OrderSalesId = model.Id;
            this.model.CustomerNumber = model.CustomerNumber;
            this.model.CustomerName = model.CustomerName;
            this.model.CustomerContact = model.CustomerContact;
            this.model.CustomerContactTel = model.CustomerContactTel;
            this.model.DeliveryDate=model.DeliveryDate;
            this.model.DeliveryLocation=model.DeliveryLocation;
            this.model.PaymentCategory=model.PaymentCategory;
            this.model.PaymentAccount=model.PaymentAccount;
            this.model.PaymentTime=model.PaymentTime;
            this.model.Transfer=model.Transfer;
            this.model.WarehouseId = model.WarehouseId;
            this.model.WarehouseName = model.WarehouseName;
            this.model.Price = model.Price;
            this.model.Count = model.Count;
            this.model.DisCount = model.DisCount;
            this.model.Remark = model.Remark;



            list.map(x => {
                var obj = new Object();
                //处理所需字段
                this.$set(obj, 'ItemId', x.ItemId);
                this.$set(obj, 'ItemCode', x.ItemCode);
                this.$set(obj, 'ItemName', x.ItemName);
                this.$set(obj, 'CurrCount', x.CurrCount);
                this.$set(obj, 'Rebate', x.Rebate);
                this.$set(obj, 'Amount', x.TaxAmount);
                this.$set(obj, 'Price', x.TaxPrice);
                this.$set(obj, 'Count', x.Count);
                this.$set(obj, 'Remark', x.Remark);
                this.$set(obj, 'Spec', x.Spec);
                this.$set(obj, 'UnitOfMeasure', x.UnitOfMeasure);
                this.tableData.push(obj);
            });
            this.calcPrice();
        },
       
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '总价';
                    return;
                }
                if (column.property === 'Amount' || column.property === 'Price') {
                    const values = data.map(item => Number(item[column.property]));


                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;

                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] += ' 元';
                    } else {
                        sums[index] = '';
                    }
                }
                else {
                    sums[index] = '';
                }

            });
            return sums;


        },

    }
}
</script>

<style></style>